<?php
namespace Superadmins\Model;
use Superadmins\Controller\PageController;
use Think\Model\RelationModel;



class SchoolModel extends RelationModel
{

	 protected $_validate =
	 	array(
	 		 array('school_name','require','学校名称必须！'), //默认情况下用正则进行验证
	 		 //array('schoo_logo','require','学校LOGO必须!'),

	 			);

	protected $_link  =
 		array(
 	
 		'SchoolRelation' => array(   
 		 'mapping_type'  => self::HAS_MANY,  
 		 'class_name'    => 'SchoolRelationView',  
 		 'foreign_key'   => 'school_id', 
 		 
 		// 'mapping_name'  => 'dept', 
 		 ),
 		'SchoolAddress' => array(   
 		 'mapping_type'  => self::HAS_ONE,  
 		 'class_name'    => 'SchoolAddress',  
 		 'foreign_key'   => 'school_id',
 		 'condition' 	=>'main=1',  
 		// 'mapping_name'  => 'dept', 
 		 ),
 		
 		 	);

	/**
	 *新增学校
	 * @return 返回学校ID
	 */
	public function add_school()
	{
		$this->create();
		$school_id=$this->add();
		return $school_id;
		
	}
	/**
	 * 新增学校地址
	 */
	public function add_address()
	{
	 $address=new SchoolAddressModel();
	 $address->addAddress();
	
	}

	/**
	 * 获取学校数据,遍历筛选条件并且分页
	 */
	public function getSchoolData($page,$show)
	{
		$SchoolRelation=new SchoolRelationViewModel();
		$map=I('get.');

		unset($map['p']);
		if(!empty($map))
		{

			if (I('get.school_name')) {
				$map_school_name['school_name'] = array('like', '%' . I('get.school_name') . '%');

				$data = $this->where($map_school_name)->getField('school_id', true);

			}

			unset($map['school_name']);
			foreach ($map as $k => $v) {
				if ($v)
				{

					if ($data)
						$where['school_id']= array('in', $data);

					if ($v != $map['school_name'])
						$where['school_type_id'] = $v;

					$data = $SchoolRelation->distinct(true)->where($where)->getField('school_id', true);

				}

			}
			$school['school_id'] = array('in',$data);
		}

		$count = $this->where($school)->count();

		$Page = new PageController($count-1, 20); // 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show = $Page->show();
		$data['show']=$show;
		$data['school_data']= $this->where($school)->limit($Page->firstRow . ',' . $Page->listRows)->select();

		return $data;


	}



	/**
	 *搜索函数集中调用
	 * @param unknown_type $model
	 * @param unknown_type $map
	 * @return unknown
	 */
	public function searchMap()
	{

		//根据条件筛选
		if(I('get.province'))
			$type_map['school_type_id'][]=array('eq',I('get.province'));
		if(I('get.city'))
		{
			$type_map['school_type_id'][]=array('eq',I('get.city'));
		}
		if(I('get.college_type'))
			$type_map['school_type_id'][]=array('eq',I('get.college_type'));
		if(I('get.school_type'))
			$type_map['school_type_id'][]=array('eq',I('get.school_type'));
		if(I('get.nature'))
			$type_map['school_type_id'][]=array('eq',I('get.nature'));
		if(I('get.attribute'))
			$type_map['school_type_id'][]=array('eq',I('get.attribute'));

		 return $type_map;

	}
	/**
	 * 获取学校详细信息
	 */
	public function getSchoolInfo($school_id)
	{

		$map['school_id'] = $school_id;
		$data['school_data'] = $this->relation(true)->where($map)->find();

		$SchoolRelation = D('SchoolRelationView');
		$data['type'] = $SchoolRelation->where($map)->select();
         $SchoolAdderss = M('SchoolAddress');
         $map['main'] = 1;
         $data['SchoolAdderss_data'] = $SchoolAdderss->where($map)->find();
	 	 $list_name=array('departments','info','professional','alumni','address');
         foreach($list_name as $k=>$val){
            	$data['info']['school_'.$val]=$this->schoolInfo(I('get.school_id'), $val);
  	        }
		 return $data;
	}

    /**
     * 获取SCHOOL所有相关表的信息
     * @param unknown_type $school_id
     * @param unknown_type $model_name
     * @return unknown
     */
    public function schoolInfo($school_id, $model_name) {
        $map['school_id'] = $school_id;
		$model_name_b='school_'.$model_name;
        $model = M($model_name_b);
        if ($model_name_b == 'school_info')
            $data = $model->where($map)->find();
        else
            $data = $model->where($map)->order($model_name.'_id desc')->select();

        return $data;
    }


 	/**
 	 * 新增或修改学校
 	 * @param unknown_type $file_url
 	 * @return boolean|Ambigous <mixed, NULL, Ambigous <NULL, mixed>, Ambigous <unknown, NULL, mixed>, \Think\mixed, boolean, string, \Think\unknown>
 	 */
 	public function addSchool($file_url)
	{
		$school_id = I('post.school_id');
		$SchoolRelation = M('SchoolRelation');
		$data = array(
			'school_name' => I('post.school_name'),
			'aliases' => I('post.aliases'),
			'school_time_year' => I('post.school_time_year'),
			'website' => I('post.website'),
		);

		if ($file_url)
			$data['logo'] = $file_url;


		//修改
		if ($school_id) {
			$data['school_id'] = $school_id;
			$this->save($data);
			$SchoolRelation->where('school_id=' . $school_id)->delete();
			$main = 1;

		} else //新增
		{
			$school_id = $this->add($data);
			$main = 0;

		}
		if ($school_id) {
			//处理学校地址属性
			$SchoolTypeProcess_data = $this->SchoolTypeProcess($school_id, I('post.'));


			if ($this->schoolRelationSave(I('post.schoolTypeId'), $school_id)) {

				$this->addAddress($main, $SchoolTypeProcess_data, $school_id);
			}
			return $school_id;
		}
		return 0;


	}

   	/**
   	 * 学校地址属性进行处理
   	 * @param unknown_type $school_id
   	 */
   	public function SchoolTypeProcess($school_id,$adress_data)
   	{
   		$SchoolType=D('SchoolType');
        $map=array('province'=>I('post.province'),
       			   'city'=>I('post.city'),
        		   'county'=>I('post.county'));
        //获取属性ID
       	$ThereAreType=$SchoolType->getThereAreType($map);
     	$adresstable=array(2=>'province_relation_id',
        			 	   3=>'city_relation_id',
        	   		       13=>'county_relation_id');
       	$i=0;

		$list_name=array(0=>'province',1=>'city',2=>'county');
     	foreach ($adresstable as $k=>$v)
     	{
     		$adress_data[$v]=$this->addressTypeAdd($school_id, $SchoolType, $ThereAreType[$list_name[$i]],$adress_data[$list_name[$i]],$k);
     		$i++;
     	}
		return $adress_data;
   	}

  /**
   * 如果地址属性不存在,新增新的地址属性并添加到关联表，如果存在直接插入关联表
   * @param unknown_type $school_id
   * @param unknown_type $SchoolType
   * @param unknown_type $address_id
   * @param unknown_type $address_name
   * @param unknown_type $sort
   * @return null
   */
  public function addressTypeAdd($school_id, $SchoolType, $address_id, $address_name, $sort) {
        $SchoolRelation = M('SchoolRelation');

        if ($address_id) {
			$data = array(
				'school_id' => $school_id,
				'school_type_id' => $address_id,
			);
			$s = $SchoolRelation->add($data);
		} else {

		  $data['school_type_name'] = $address_name;
		  $data['school_type_sort'] = $sort;

		  $school_type_id = $SchoolType->add($data);

		  $SchoolRelationData['school_id'] = $school_id;
		  $SchoolRelationData['school_type_id'] = $school_type_id;
		  $s = $SchoolRelation->add($SchoolRelationData);

		}
	  return $s;
}
   	/**
   	 * 批量批量新增关联属性
   	 * @param unknown_type $schoolTypeId
   	 */
	public function schoolRelationSave($schoolTypeId,$school_id)
	{
		$SchoolRelation=M('SchoolRelation');
		if (isset($schoolTypeId)) {

			//组装并且一次性插入数据
			foreach ($schoolTypeId as $v) {
				$array[] = array(
					'school_id' => $school_id,
					'school_type_id' => $v,
				);
			}

			return $SchoolRelation->addAll($array);

		}
	}

	/**
	 * 新增或修改地址
	 * @param $main=1 则更新,0则新增
	 * @param $data
			*/
			public function addAddress($main,$data,$school_id)
		{
			if(!$data['school_id'])
				$data['school_id']=$school_id;

			$SchoolAddress=M('SchoolAddress');
			if($main)
			{

				$map['school_id']=$data['school_id'];
				$map['main']=$main;
				$SchoolAddress->where($map)->save($data);

			}
			else
			{

				$SchoolAddress->add($data);
			}


	}



}